package org.yunai.swjg.server.core.service;

import org.yunai.swjg.server.core.message.GameMessage;
import org.yunai.swjg.server.core.session.GameSession;
import org.yunai.yfserver.command.MessageDispatcher;
import org.yunai.yfserver.plugin.mina.command.AbstractMinaMessageCommand;

import java.lang.reflect.ParameterizedType;

/**
 * 游戏消息命令基类
 * User: yunai
 * Date: 13-3-28
 * Time: 下午8:17
 */
public abstract class GameMessageCommand<M extends GameMessage>
        extends AbstractMinaMessageCommand<GameSession, M> {

    /**
     * 自动将消息加入到MessageDispatcher
     */
    public GameMessageCommand() {
        MessageDispatcher.getInstance().register(this);
    }

    /**
     * 检查Online是否还在线，如果不在线，则不进行命令调用
     *
     * @param session 会话
     * @param msg 消息
     */
    @Override
    public final void execute(GameSession session, M msg) {
        Online online = session.getOnline();
        if (online == null || !online.isConnected()) {
            return;
        }
        execute(online, msg);
    }

    /**
     * 子类实现命令执行
     *
     * @param online 在线信息
     * @param msg 消息
     */
    protected abstract void execute(Online online, M msg);

    /**
     * 通过反射获得子类消息编号
     * @return 子类消息编号
     */
    @Override
    public final short getCode() {
        try {
            ParameterizedType pt = (ParameterizedType) getClass().getGenericSuperclass();
            Class type = (Class) pt.getActualTypeArguments()[0];
            return (short) type.getField("CODE").get(type);
        } catch (IllegalAccessException | NoSuchFieldException e) {
            throw new RuntimeException(e);
        }
    }
}